#include "stockfileparser.h"
#include "candle.h"
#include <cstring>
#include <iostream>
#include <list>
#include <fstream>
#include <vector>
#include <cstdlib>


//qt porting
#include <QFile>
#include <QString>
#include <QStringList>
#include <QTextStream>
#include <QIODevice>
#include <QDateTime>

//wrapper classes
#include "ohlcvset.h"
#include "ohlcv.h"


//using qDebug()
#include <QtGui>

StockFileParser::StockFileParser()
{
}


bool StockFileParser::isSingleStockFile(const QString filePath){
    return isSingleStockFile(new QFile(filePath));
}


bool StockFileParser::isSingleStockFile(QFile *readFile){

    const QString header ("Date,Open,High,Low,Close,Volume,Adj Close");

    //handle error
    if (!readFile->open(QIODevice::ReadOnly)){
        return false;
    }

    QString line;
    QTextStream stream(readFile);
    line = stream.readLine();

    return (line == header);

}



OHLCVSet StockFileParser::getSingleStockSet(const QString filePath, QString stockName){
    return getSingleStockSet(new QFile(filePath), stockName);
}

OHLCVSet StockFileParser::getSingleStockSet(QFile *readFile, QString stockName)
{


    OHLCVSet cjto;// = new OHLCVSet();


    //handle error
    if (!readFile->open(QIODevice::ReadOnly)){
        qDebug()<<"Could not open " << readFile->fileName();
        return cjto;
    }

    QTextStream textStream(readFile);
    QDateTime timestamp;

    //pulando a primeira linha
    textStream.readLine();

    while (!textStream.atEnd()){
        QString line =  textStream.readLine();
        QStringList lineData = line.split(",");

        timestamp = QDateTime::fromString(lineData.at(0), "yyyy-MM-dd");

        long  date   = timestamp.toTime_t();
        float open   = lineData.at(1).toFloat();
        float high   = lineData.at(2).toFloat();
        float low    = lineData.at(3).toFloat();
        float close  = lineData.at(4).toFloat();
        float volume = lineData.at(5).toFloat();

        const OHLCVItem *aux = new OHLCVItem(new QString(stockName), open, high, low, close, volume, date);
        cjto.append(*aux);

    }


    qSort(cjto);
    return cjto;


}


